import { Category, Transaction } from '../models/index.js';
import Joi from 'joi';

// 验证分类数据的Schema
const categorySchema = Joi.object({
  name: Joi.string().max(50).required(),
  type: Joi.string().valid('income', 'expense').required(),
  icon: Joi.string().default('default'),
  color: Joi.string().default('#4F46E5'),
  sortOrder: Joi.number().default(0)
});

// 获取所有分类
export const getAllCategories = async (req, res) => {
  try {
    const where = {}; // 暂时不过滤isActive，避免字段映射问题
    
    if (req.query.type) {
      where.type = req.query.type;
    }

    const categories = await Category.findAll({
      where,
      order: [['sortOrder', 'ASC'], ['createdAt', 'ASC']]
    });

    res.json({
      status: 'success',
      data: { categories }
    });
  } catch (error) {
    res.status(500).json({
      status: 'error',
      message: '获取分类失败',
      error: error.message
    });
  }
};

// 获取单个分类
export const getCategoryById = async (req, res) => {
  try {
    const category = await Category.findByPk(req.params.id);

    if (!category) {
      return res.status(404).json({
        status: 'error',
        message: '分类不存在'
      });
    }

    res.json({
      status: 'success',
      data: { category }
    });
  } catch (error) {
    res.status(500).json({
      status: 'error',
      message: '获取分类失败',
      error: error.message
    });
  }
};

// 创建新分类
export const createCategory = async (req, res) => {
  try {
    // 验证数据
    const { error, value } = categorySchema.validate(req.body);
    if (error) {
      return res.status(400).json({
        status: 'error',
        message: '数据验证失败',
        details: error.details[0].message
      });
    }

    const category = await Category.create(value);

    res.status(201).json({
      status: 'success',
      message: '分类创建成功',
      data: { category }
    });
  } catch (error) {
    if (error.name === 'SequelizeUniqueConstraintError') {
      return res.status(400).json({
        status: 'error',
        message: '该类型下已存在同名分类'
      });
    }
    
    res.status(500).json({
      status: 'error',
      message: '创建分类失败',
      error: error.message
    });
  }
};

// 更新分类
export const updateCategory = async (req, res) => {
  try {
    // 验证数据
    const { error, value } = categorySchema.validate(req.body);
    if (error) {
      return res.status(400).json({
        status: 'error',
        message: '数据验证失败',
        details: error.details[0].message
      });
    }

    const [updatedRowsCount] = await Category.update(value, {
      where: { id: req.params.id }
    });

    if (updatedRowsCount === 0) {
      return res.status(404).json({
        status: 'error',
        message: '分类不存在'
      });
    }

    const category = await Category.findByPk(req.params.id);

    res.json({
      status: 'success',
      message: '分类更新成功',
      data: { category }
    });
  } catch (error) {
    if (error.name === 'SequelizeUniqueConstraintError') {
      return res.status(400).json({
        status: 'error',
        message: '该类型下已存在同名分类'
      });
    }

    res.status(500).json({
      status: 'error',
      message: '更新分类失败',
      error: error.message
    });
  }
};

// 删除分类
export const deleteCategory = async (req, res) => {
  try {
    const category = await Category.findByPk(req.params.id);

    if (!category) {
      return res.status(404).json({
        status: 'error',
        message: '分类不存在'
      });
    }

    // 检查是否为系统预设分类
    if (category.isSystem) {
      return res.status(400).json({
        status: 'error',
        message: '系统预设分类不能删除'
      });
    }

    // 检查是否有交易记录使用此分类
    const transactionCount = await Transaction.count({ 
      where: { categoryId: req.params.id }
    });
    if (transactionCount > 0) {
      return res.status(400).json({
        status: 'error',
        message: `该分类下还有 ${transactionCount} 条交易记录，无法删除。请先删除相关交易记录或将其改为其他分类。`
      });
    }

    await Category.destroy({
      where: { id: req.params.id }
    });

    res.json({
      status: 'success',
      message: '分类删除成功'
    });
  } catch (error) {
    res.status(500).json({
      status: 'error',
      message: '删除分类失败',
      error: error.message
    });
  }
};

// 初始化默认分类
export const initializeDefaultCategories = async (req, res) => {
  try {
    // 检查是否已有分类
    const existingCategories = await Category.count();
    if (existingCategories > 0) {
      return res.status(400).json({
        status: 'error',
        message: '已存在分类，无需初始化'
      });
    }

    // 默认收入分类
    const incomeCategories = [
      { name: '工资收入', type: 'income', icon: 'salary', color: '#10B981', sortOrder: 1, isSystem: true },
      { name: '奖金', type: 'income', icon: 'bonus', color: '#F59E0B', sortOrder: 2, isSystem: true },
      { name: '投资收益', type: 'income', icon: 'investment', color: '#3B82F6', sortOrder: 3, isSystem: true },
      { name: '兼职收入', type: 'income', icon: 'part-time', color: '#8B5CF6', sortOrder: 4, isSystem: true },
      { name: '其他收入', type: 'income', icon: 'other', color: '#6B7280', sortOrder: 5, isSystem: true }
    ];

    // 默认支出分类
    const expenseCategories = [
      { name: '餐饮', type: 'expense', icon: 'food', color: '#EF4444', sortOrder: 1, isSystem: true },
      { name: '交通', type: 'expense', icon: 'transport', color: '#F97316', sortOrder: 2, isSystem: true },
      { name: '购物', type: 'expense', icon: 'shopping', color: '#EC4899', sortOrder: 3, isSystem: true },
      { name: '娱乐', type: 'expense', icon: 'entertainment', color: '#8B5CF6', sortOrder: 4, isSystem: true },
      { name: '医疗', type: 'expense', icon: 'medical', color: '#06B6D4', sortOrder: 5, isSystem: true },
      { name: '教育', type: 'expense', icon: 'education', color: '#84CC16', sortOrder: 6, isSystem: true },
      { name: '住房', type: 'expense', icon: 'housing', color: '#F59E0B', sortOrder: 7, isSystem: true },
      { name: '通讯', type: 'expense', icon: 'communication', color: '#3B82F6', sortOrder: 8, isSystem: true },
      { name: '其他支出', type: 'expense', icon: 'other', color: '#6B7280', sortOrder: 9, isSystem: true }
    ];

    // 批量创建分类
    await Category.bulkCreate([...incomeCategories, ...expenseCategories]);

    res.json({
      status: 'success',
      message: '默认分类初始化成功',
      data: {
        incomeCount: incomeCategories.length,
        expenseCount: expenseCategories.length
      }
    });
  } catch (error) {
    res.status(500).json({
      status: 'error',
      message: '初始化默认分类失败',
      error: error.message
    });
  }
};